package com.icesoft.base.manager.service.security;

import com.icesoft.base.manager.entity.security.RelSysRoleOrg;
import com.icesoft.core.dao.base.BaseDao;
import com.icesoft.core.dao.criteria.QueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RelSysRoleOrgService extends BaseDao<RelSysRoleOrg> {

    public void deleteOrgRelation(int orgId) {
        delete(QueryBuilder.get("orgId", orgId));
    }

    public void deleteRoleRelation(int roleId) {
        delete(QueryBuilder.get("roleId", roleId));
    }

    @Transactional
    public void updateRoleOrg(int roleId, List<Integer> ownerOrgIds) {
        List<RelSysRoleOrg> list = findByRoleId(roleId);
        List<RelSysRoleOrg> deleteList = new ArrayList<>();
        for (RelSysRoleOrg orgOwner : list) {
            if (ownerOrgIds.contains(orgOwner.getOrgId())) {// 包含表示一致，不用处理
                ownerOrgIds.remove(new Integer(orgOwner.getOrgId()));
            } else {
                deleteList.add(orgOwner);// 不包含，需要删除
            }
        }
        delete(deleteList);
        for (int orgOwnerId : ownerOrgIds) {
            RelSysRoleOrg orgOwner = new RelSysRoleOrg();
            orgOwner.setOrgId(orgOwnerId);
            orgOwner.setRoleId(roleId);
            create(orgOwner);
        }
    }

    public List<RelSysRoleOrg> findByRoleId(int roleId) {
        return find(QueryBuilder.get("roleId", roleId));
    }

    public List<Integer> findOrgIdByRoleId(int roleId) {
        List<Integer> ids = new ArrayList<>();
        if (roleId == 0) {
            return ids;
        }
        List<RelSysRoleOrg> list = findByRoleId(roleId);
        return list.stream().map(RelSysRoleOrg::getOrgId).collect(Collectors.toList());
    }
}
